#coding=utf-8
import wx
import os
import base64
import random

#自定义模块
import mail
import account

def icon2Bmp(icon):
    """
    args:
      wx.Icon icon
    return wx.Bitmap
    """
    bmp = wx.EmptyBitmap( icon.GetWidth(), icon.GetHeight())
    bmp.CopyFromIcon( icon ) 
    return bmp

def getFileIcon(fileExt):
    """
    getFileIcon(str fileExt) -> wx.Icon
    
     获取file扩展名相关的Icon
    """
    mimeTypeManager=wx.MimeTypesManager()
    defaultIcon=wx.ArtProvider_GetIcon(wx.ART_NORMAL_FILE, wx.ART_OTHER, (48,48))
    
    nolog=wx.LogNull() #可以抑制获取图标时弹出错误消息匡但无excpetion的情况,使用完请删除
                       #参考:http://blog.donews.com/limodou/archive/2005/12/26/671633.aspx 
    fileType=mimeTypeManager.GetFileTypeFromExtension( fileExt )
    
    if fileType is None:
        return defaultIcon
    
    iconInfo=fileType.GetIconInfo()
    if iconInfo is None:
        return defaultIcon
    
    icon = iconInfo[0]#icon, file, index = iconInfo
    if not icon.Ok():
       return defaultIcon
   
    del nolog
    return icon
class MainListBook(wx.Listbook):
    def __init__(self, parent, id):
        wx.Listbook.__init__(self, parent, id, style=wx.LB_DEFAULT)
        sty=wx.BORDER_SUNKEN
        self.il=wx.ImageList(48,48)
        icondoc=wx.Bitmap('./icon/doc.ico',wx.BITMAP_TYPE_ICO)
        iconmedia=wx.Bitmap('./icon/media.ico',wx.BITMAP_TYPE_ICO)
        iconpic=wx.Bitmap('./icon/pic.ico',wx.BITMAP_TYPE_ICO)
        self.il.Add(icondoc)
        self.il.Add(iconpic)
        self.il.Add(iconmedia)
        self.AssignImageList(self.il)
        self.doc=wx.ListCtrl(self,style=wx.LC_ICON|wx.LC_AUTOARRANGE)
        self.pic=wx.ListCtrl(self,style=wx.LC_ICON)
        self.media=wx.ListCtrl(self,style=wx.LC_ICON)
        self.il2=wx.ImageList(32,32)
        self.il3=wx.ImageList(32,32)
        self.sysicon=['.py','.mdb','.hlp','.zip','.txt','.rar', \
                      '.chm','.gz','.jpg','.gif','.ini','.pdf','.mp3',\
                      '.rm','.rmvb','.wma','.wav','.html','.htm','.php',\
                      '.bat','.png']
        iconone=wx.Bitmap('./icon/one.ico',wx.BITMAP_TYPE_ICO)
        self.il2.Add(iconone)
        self.il3.Add(iconone)
        for ext in self.sysicon:
            icon=getFileIcon(ext)
            bmp=icon2Bmp(icon)
            self.il2.Add(bmp)
            self.il3.Add(bmp)

        self.doc.AssignImageList(self.il2,wx.IMAGE_LIST_NORMAL)
        self.pic.AssignImageList(self.il3,wx.IMAGE_LIST_NORMAL)
##        self.media.AssignImageList(self.il2,wx.IMAGE_LIST_NORMAL)

        #绑定事件
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnList_item_selected_doc, self.doc)
        self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected_doc, self.doc)
        self.doc.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClick)
        self.doc.Bind(wx.EVT_RIGHT_UP, self.OnRightClick)
        self.doc.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick_doc)

        self.AddPage(self.doc,u"文档",imageId=0)
        self.AddPage(self.pic,u"图片",imageId=1)
        self.AddPage(self.media,u"音乐",imageId=2)
        self.selectlist=[]
        self.currentitem=None

        try:
            self.readmailbox()
        except:

            dlg = wx.MessageDialog(self, u'邮箱服务不能使用，文件列表读取失败。',
                               u'出错提示',
                               wx.OK | wx.ICON_WARNING
                               #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION
                               )
            dlg.ShowModal()
            dlg.Destroy()
            

##        for x in range(1,30):
##            self.doc.InsertImageStringItem(0,str(x)+fileext,0)
##
            
    def readmailbox(self):  #读取邮箱文件列表
        self.m=mail.eximap(account.mailimap)
        self.m.login(account.mailuser,account.mailpass)
        filelist=self.m.listfile()
        self.doc.ClearAll()
        self.selectlist=[]
        for x in filelist:
            fname=x[4]
            fileext=os.path.splitext(fname)[1].lower()
            if fileext in self.sysicon:
                iconid=self.sysicon.index(fileext)+1
            else:
                iconid=0
            if x[1]=='doc':
                _id=self.doc.InsertImageStringItem(0,fname,iconid)
            elif x[1]=='pic':
                _id=self.pic.InsertImageStringItem(0,fname,iconid)
            else:
                _id=self.media.InsertImageStringItem(0,fname,iconid)
            if x[5]=='additon':
                self.doc.SetItemData(_id,int(x[7]))
            else:
                self.doc.SetItemData(_id,int(x[5]))
        
    def OnItemDeselected_doc(self,evt):
        item = evt.GetItem()
        id=item.GetId()
        self.selectlist.remove(id)
        #print "Deselected :",id, "  list:  ",self.selectlist
        
    def OnList_item_selected_doc(self,evt):
        item = evt.GetItem()
        id=item.GetId()
        self.currentitem=id
        self.selectlist.append(id)
        #print "Select item: ",self.currentitem, " Select Count: ",self.doc.GetSelectedItemCount()  ,"  list:  ",self.selectlist
        
    def OnDoubleClick_doc(self, evt):
        print "Double Click to download file"
        self.downloadfile()                
        
    def downloadfile(self): #下载文件
        path=''

        dlg = wx.DirDialog(self, "Choose a directory:",style=wx.DD_DEFAULT_STYLE)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
        dlg.Destroy()

        if path!='':
            if os.path.exists(path):
                for f in self.selectlist:
                    fileid=self.doc.GetItemData(f)
                    filename=self.doc.GetItemText(f)
                    fp=open(path+'/'+filename,'wb')
                    data=self.m.download(fileid)
                    data=base64.decodestring(data)
                    fp.write(data)
                    fp.close()
                print "Save file to ",path
            else:
                print "Path does not exist"
        else:
            print "Save canceled"
        
    def OnRightClick(self, event):   #右点鼠标，显示菜单
        # only do this part the first time so the events are only bound once
        if not hasattr(self, "popupID1"):
            self.popupID1 = wx.NewId()
            self.popupID2 = wx.NewId()
            self.popupID3 = wx.NewId()
            self.popupID4 = wx.NewId()
            self.popupID5 = wx.NewId()
            self.popupID6 = wx.NewId()

            self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1)
            self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2)
            self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3)
            self.Bind(wx.EVT_MENU, self.OnPopupFour, id=self.popupID4)
            self.Bind(wx.EVT_MENU, self.OnPopupFive, id=self.popupID5)
            self.Bind(wx.EVT_MENU, self.OnPopupSix, id=self.popupID6)

        # make a menu
        menu = wx.Menu()
        # add some items
        menu.Append(self.popupID1, u"下载")
        menu.Append(self.popupID2, u"删除")
        menu.Append(self.popupID3, u"上传文件")
        menu.Append(self.popupID4, u"未用")
        menu.Append(self.popupID5, u"未用")
        menu.Append(self.popupID6, u"刷新")

        # Popup the menu.  If an item is selected then its handler
        # will be called before PopupMenu returns.
        self.PopupMenu(menu)
        menu.Destroy()

    def OnPopupOne(self, event): #下载菜单处理
        st=u"下载文件:"+str(self.selectlist)
        if len(self.selectlist)>0:
            self.downloadfile()
            
    def OnPopupTwo(self, event): #删除菜单处理
        if len(self.selectlist)>0:
            for f in self.selectlist:
                fileid=self.doc.GetItemData(f)
                print 'STORE',str(fileid), '+FLAGS', '\\Deleted'
                self.m.store(fileid, '+FLAGS', '\\Deleted')
            self.m.expunge()
            self.readmailbox()

    def OnPopupThree(self, event): #上传菜单处理
        wildcard = "All files (*.*)|*.*"   
        paths=[]
        dlg = wx.FileDialog(
            self, message="Upload", defaultDir=os.getcwd(), 
            defaultFile='', wildcard=wildcard, style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR
            )
        dlg.SetFilterIndex(1)
        if dlg.ShowModal() == wx.ID_OK:
            paths = dlg.GetPaths()
        dlg.Destroy()
        print u'上传文件：%d个 ' % len(paths)
        if len(paths)>0 :
            for path in paths:
                if os.path.exists(path):
                    print u"    正在上传文件%s ..."%path                
                    s=mail.filesender(account.mailsmtp)
                    s.login(account.smtpuser,account.smtppass)
                    s.sendfile(path, 'doc')  #path.encode('GBK')
                    print u"    文件%s上传完毕"%path
            self.readmailbox()

    def OnPopupFour(self, event):
        pass
    def OnPopupFive(self, event):
        pass
    def OnPopupSix(self, event): #刷新处理
        self.readmailbox()        

if __name__=='__main__':
    import pocketdisk
